const cloud = require('wx-server-sdk')
const axios = require("axios")

cloud.init({
    env: "malu-9gjr8vrn08c2dfb4"
})

const db = cloud.database()

exports.main = async (event, context) => {

    // 假如有500条
    let count = await db.collection("playList").count(); // 得到所有的数据条数
    let batch = Math.ceil(count.total / 100) // 取的次数
    let stack = []; // 取出来的数据都放到stack中
    for (let i = 0; i < batch; i++) {
        let list = await db.collection("playList").skip(i * 100).get();
        stack = stack.concat(list.data)
    }

    // list是数据库中的数据   list和playList可能有重复的数据，需要去重
    // db.collection("playList").get()最多一次可以获取100条数据
    // let list = await db.collection("playList").get();

    // playList是调用接口得到的数据
    let response = await axios.get("http://47.94.210.129:3002/personalized");
    let playList = response.data.result;

    let res = []; // 放去重后的数据
    for (let item of playList) {
        let flag = true;
        // for (let subject of list.data) {
        for (let subject of stack) {
            if (subject.id === item.id) {
                flag = false;
            }
        }
        if (flag) {
            res.push(item)
        }
    }

    for (let i = 0; i < res.length; i++) {
        db.collection("playList").add({
            data: {
                ...res[i],
                createTime: db.serverDate()
            }
        })
    }

    return "hello"
}